package spitter.repository;

import domain.Spitter;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.inject.Inject;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class JdbcSpitterRepository {

    private JdbcOperations jdbcOperations;

    @Inject
    public JdbcSpitterRepository(JdbcOperations jdbcOperations) {
        this.jdbcOperations = jdbcOperations;
    }

    public void addSpitter(Spitter spitter) {
        String INSERT_SPITTER = "insert into spitter(username,password,email) values()";
        jdbcOperations.update(INSERT_SPITTER,
                spitter.getUserName(),
                spitter.getPassword(),
                spitter.getEmail());

    }

    public Spitter findOne(long id) {
//        return jdbcOperations.queryForObject(
//                "select id,username,password,fullname,email from spitter "
//                , new SpitterRowMapper(), id);
        //la
        return jdbcOperations.queryForObject(
                "select id,username,password,fullname,email from spitter where id=?",
                    (rs, i) -> new Spitter(
                        rs.getString("username"),
                        rs.getString("fullname"),
                        rs.getString("email"),
                        rs.getString("password"),
                        rs.getInt("id")
                ), id);
    }

    public static final class SpitterRowMapper implements RowMapper<Spitter> {
        public Spitter mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new Spitter(
                    rs.getString("username"),
                    rs.getString("fullname"),
                    rs.getString("email"),
                    rs.getString("password"),
                    rs.getInt("id")
            );
        }
    }


}
